# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.TimingSwitch import TimingSwitch


class GetTimingSwitch(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        print(self.request.path)
        ojson = None
        r = WrapCursor.WrapCursor()

        try:
            ojson = json.loads(self.request.body)
            did = ojson['id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except:
            self.write(r.Error('request data error'))
            return

        s = Session()
        if did == -1:
            filt = dict()
        else:
            filt = {'id': did}
        tms = s.query(TimingSwitch).filter_by(**filt).all()
        data = list()
        jsonret = {'Code': 0, 'desc': u'成功'}
        for t in tms:
            o = dict()
            o["Opt"] = t.OptTypeID
            o["weekday"] = t.weekDay
            o["IsRunning"] = t.IsRunning
            o["sunup_lightoff"] = t.sunup_lightoff
            o["sunup_lighton"] = t.sunup_lighton
            o["sunup_lightoff_delay_seconds"] = t.sunup_lightoff_delay
            o["sunup_lighton_delay_seconds"] = t.sunup_lighton_delay
            o["sundown_lighton"] = t.sundown_lighton
            o["sundown_lightoff_delay_seconds"] = t.sundown_lightoff_delay
            o["sundown_lighton_delay_seconds"] = t.sundown_lighton_delay
            o["sundown_lightoff"] = t.sundown_lightoff
            o["PointID"] = t.PointID
            o["enable"] = t.enable
            o["Params"] = t.Params
            o["daytime"] = t.everyDay
            o["WallTime"] = t.wallTime
            o["id"] = t.id
            o["desc"] = t.desc
            data.append(o)
        jsonret['data'] = data
        self.write(json.dumps(jsonret))
        return
